package com.hutou.chuangke.activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.hutou.chuangke.Bean.CollBean;
import com.hutou.chuangke.Bean.TalkBean;
import com.hutou.chuangke.MainApplication;
import com.hutou.chuangke.R;
import com.hutou.chuangke.adapter.ImageGridviewAdapter;
import com.hutou.chuangke.androidbug.AndroidBug5497Workaround;
import com.hutou.chuangke.net.HttpUtil;
import com.hutou.chuangke.net.RequestThreadPool;
import com.hutou.chuangke.net.http.HttpUrl;
import com.hutou.chuangke.net.http.User;
import com.hutou.chuangke.uitl.CommonUtils;
import com.hutou.chuangke.widget.CircleImageView;
import com.hutou.chuangke.widget.DividerItemDecoration;
import com.hutou.chuangke.widget.MyGridview;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/21.
 */

public class TrackDetailActivity extends BaseActivity implements View.OnClickListener {
    Toolbar toolbar;
    RecyclerView track_detail_recyclerviewew;
    Context mContext;
    TrackDetailAdapter adapter;
    private ArrayList<CollBean> mData = new ArrayList<>();
    private TalkBean talkBean;
    ImageGridviewAdapter indexSoundAdapter;
    private static final String NET_PATH = "talkimgs/";
    LoadCollListInfo loadCollListInfo;
    RequestSend requestSend;
    Requestpraise requestpraise;
    Requestcancelpraise requestcancelpraise;
    RequestReply requestReply;
    private EditText colle_et;
    private Button send_bt;
    private String strcoll;
    private LinearLayoutManager manger;
    TextView nametv, datetv, contexttv, addresstv, commenttv, praise_usernametv,isfollow_tv;
    ImageView headiv, commentiv, shareiv;
    LinearLayout praise_layout;
    FrameLayout add_view_layout;
    MyGridview gridview;
    CheckBox praiseiv;
    private String colleid;//评论id 用于回复
    private String colluserid;//评论者id
    private boolean isReply;//是否为回复状态

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_track_detail);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mContext = TrackDetailActivity.this;
        init();
        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        AndroidBug5497Workaround.assistActivity(this);
    }

    private void init() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setPadding(0, CommonUtils.getStatusHeight(TrackDetailActivity.this), 0, 0);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.actionbar_back);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setTitle("评论");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        showQuickControl(false);
        track_detail_recyclerviewew = (RecyclerView) findViewById(R.id.track_detail_recyclerviewew);
        manger = new LinearLayoutManager(mContext);
        track_detail_recyclerviewew.setLayoutManager(manger);
        track_detail_recyclerviewew.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL_LIST));
        adapter = new TrackDetailAdapter();
        track_detail_recyclerviewew.setAdapter(adapter);
        adapter.setonItemListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                isReply = true;
                colle_et.setHint("回复："+mData.get(position).getSinger());
                colleid = mData.get(position).getId();
                colluserid = mData.get(position).getTageruserid();
            }
        });

        nametv = (TextView) findViewById(R.id.nametv);//昵称
        datetv = (TextView) findViewById(R.id.datetv);//时间
        contexttv = (TextView) findViewById(R.id.contexttv);//发布内容
        addresstv = (TextView) findViewById(R.id.addresstv);//地址
        commenttv = (TextView) findViewById(R.id.commenttv);//评论人数
        praise_usernametv = (TextView) findViewById(R.id.praise_usernametv);//点赞人名
        headiv = (ImageView) findViewById(R.id.headiv);//头像
        commentiv = (ImageView) findViewById(R.id.commentiv);//评论按钮
        praiseiv = (CheckBox) findViewById(R.id.praiseiv);//点赞按钮
        shareiv = (ImageView) findViewById(R.id.shareiv);//分享按钮
        praise_layout = (LinearLayout) findViewById(R.id.praise_layout);//点赞人名布局
        add_view_layout = (FrameLayout) findViewById(R.id.add_view_layout);
        gridview = (MyGridview) findViewById(R.id.gridview);
        isfollow_tv = (TextView) findViewById(R.id.isfollow_tv);


        send_bt = (Button) findViewById(R.id.send_bt);
        send_bt.setOnClickListener(this);
        colle_et = (EditText) findViewById(R.id.colle_et);
        Intent intent = getIntent();
        talkBean = (TalkBean) intent.getSerializableExtra("track");
    }

    private void initData() {
        nametv.setText(talkBean.getNickname());
        datetv.setText(talkBean.getCrttm());
        contexttv.setText(talkBean.getNote());
        ImageLoader.getInstance().displayImage(talkBean.getUimg(), headiv);
        if(!talkBean.getImgs().equals("")){
            List<String> list = new ArrayList<>();
            String[] sourceStrArray = talkBean.getImgs().split(",");
            for(String str: sourceStrArray){
                list.add(str);
            }
            if(list.size()>0) {
                indexSoundAdapter = new ImageGridviewAdapter(mContext, list);
                gridview.setAdapter(indexSoundAdapter);
            }
        }
        commenttv.setText(talkBean.getCollectnum()>999?999+"":talkBean.getCollectnum()+"");
        if(talkBean.getIsfollow().equals("y")){
            isfollow_tv.setText("已关注");
            isfollow_tv.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
        }else{
            isfollow_tv.setText("关注");
            isfollow_tv.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.add),null,null,null);
        }
        if(talkBean.getIszan()!=null) {
            if (talkBean.getIszan().equals("y")) {
                praiseiv.setChecked(true);
            } else {
                praiseiv.setChecked(false);
            }
        }else {
            praiseiv.setChecked(false);
        }
        praiseiv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(praiseiv.isChecked()){//点赞
                    requestpraise = new Requestpraise();
                    requestpraise.execute(talkBean.getId()+"");
                }else{//取消点赞
                    requestcancelpraise = new Requestcancelpraise();
                    requestcancelpraise.execute(talkBean.getHouseid()+"");
                }
            }
        });

        loadCollListInfo = new LoadCollListInfo();
        loadCollListInfo.execute(talkBean.getId()+"");
    }

    @Override
    public void onClick(View v) {
        if(v == send_bt){
            strcoll = colle_et.getText().toString();
            if(strcoll.equals("")){
                Toast.makeText(mContext,"请填写评论",Toast.LENGTH_SHORT).show();
                return;
            }
            if(isReply) {//是否在回复状态
                requestReply = new RequestReply();
//                requestReply.execute(bean.getId());
                requestReply.execute(talkBean.getId()+"",colluserid,colleid);
            }else{
                requestSend = new RequestSend();
                requestSend.execute(talkBean.getId()+"");
            }
        }
    }

    /***
     * 回复评论
     * params[0] 音乐id
     * params[1] 评论者的id
     * params[2] 回复数据id
     * */
    class RequestReply extends AsyncTask<String,Void,Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {
            try{
                JsonObject jsonObject = HttpUtil.getResposeJsonObject(HttpUrl.GET_TO_HF,
                        User.getToHf(params[0],"4",strcoll,params[1],MainApplication.id,params[2]));
                String flag = jsonObject.get("flag").getAsString();
                if(flag.equals("1")){
                    return true;
                }
                return false;
            }catch(Exception e){
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean comlete) {
            if(comlete){
                isReply = false;
                Toast.makeText(mContext,"回复成功",Toast.LENGTH_SHORT).show();
                loadCollListInfo = new LoadCollListInfo();
                loadCollListInfo.execute(talkBean.getId()+"");
                colle_et.setText("");
                colle_et.setHint("");
                MoveToPosition(manger,track_detail_recyclerviewew,0);
                closeInputMethod();
            }else{
                Toast.makeText(mContext,"回复失败",Toast.LENGTH_SHORT).show();
            }
        }

        public void cancleTask(){
            cancel(true);
            RequestThreadPool.finish();
        }
    }


    class RequestSend extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... params) {
            try{
                mData.clear();
                JsonObject jsonObject = HttpUtil.getResposeJsonObject(HttpUrl.GET_TO_CT,
                        User.getToCt(params[0],"4",strcoll,MainApplication.id));
                String flag = jsonObject.get("flag").getAsString();
                if(flag.equals("1")){
                    return true;
                }
                return false;
            }catch(Exception e){
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean comlete) {
            if(comlete){
                Toast.makeText(mContext,"评论成功",Toast.LENGTH_SHORT).show();
                loadCollListInfo = new LoadCollListInfo();
                loadCollListInfo.execute(talkBean.getId()+"");
                colle_et.setText("");
                MoveToPosition(manger,track_detail_recyclerviewew,0);
                closeInputMethod();
            }else{
                Toast.makeText(mContext,"评论失败",Toast.LENGTH_SHORT).show();
            }
        }

        public void cancleTask(){
            cancel(true);
            RequestThreadPool.finish();
        }
    }

    private void closeInputMethod(){
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }
    /**
     * RecyclerView 移动到当前位置，
     *
     * @param manager   设置RecyclerView对应的manager
     * @param mRecyclerView  当前的RecyclerView
     * @param n  要跳转的位置
     */
    public static void MoveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {


        int firstItem = manager.findFirstVisibleItemPosition();
        int lastItem = manager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = mRecyclerView.getChildAt(n - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);
        } else {
            mRecyclerView.scrollToPosition(n);
        }

    }

    class LoadCollListInfo extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... params) {
            try{
                mData.clear();
                JsonObject jsonObject = HttpUtil.getResposeJsonObject(User.getCByAlbId(params[0],"4"));
                String flag = jsonObject.get("flag").getAsString();
                JsonArray colllist = jsonObject.get("collList").getAsJsonArray();
                for(JsonElement element : colllist){
                    mData.add(MainApplication.gsonInstance().fromJson(element,CollBean.class));
                }

            }catch(Exception e){
                e.printStackTrace();
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean comlete) {
            adapter.setData(mData);
            adapter.notifyDataSetChanged();

        }

        public void cancleTask(){
            cancel(true);
            RequestThreadPool.finish();
        }
    }

    private View crateHeadview() {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(R.layout.loading_circle, null);
        return view;
    }

    Handler handler = new Handler();

    /**点赞请求*/
    class Requestpraise extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... params) {
            try{
                JsonObject list = HttpUtil.getResposeJsonObject(User.houseinto(MainApplication.id,MainApplication.sid,"2","5",params[0]));
                String flag = list.get("flag").getAsString();
                if(flag.equals("1")){
                    return true;
                }
                return false;
            }catch(Exception e){
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean comlete) {
            if(comlete){
                Toast.makeText(mContext,"点赞成功",Toast.LENGTH_SHORT).show();
            }

        }

        public void cancleTask(){
            cancel(true);
            RequestThreadPool.finish();
        }
    }

    /**取消点赞请求*/
    class Requestcancelpraise extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... params) {
            try{
                JsonObject list = HttpUtil.getResposeJsonObject(User.houseDel(MainApplication.id,MainApplication.sid,params[0]));
                String flag = list.get("flag").getAsString();
                if(flag.equals("1")){
                    return true;
                }
                return false;
            }catch(Exception e){
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean comlete) {
            if(comlete){
                Toast.makeText(mContext,"取消点赞",Toast.LENGTH_SHORT).show();
            }
        }
        public void cancleTask(){
            cancel(true);
            RequestThreadPool.finish();
        }
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    class TrackDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        final static int FIRST_ITEM = 0;
        final static int ITEM = 1;
        private ArrayList<CollBean> mData = new ArrayList<>();
        private OnItemClickListener mOnItemClickListener;

        public void setonItemListener(OnItemClickListener mOnItemClickListener) {
            this.mOnItemClickListener = mOnItemClickListener;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ListItemViewHolder(LayoutInflater.from(mContext)
                        .inflate(R.layout.item_comment, null));
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof ListItemViewHolder) {
                CollBean bean = mData.get(position);
                ((ListItemViewHolder)holder).nametv.setText(bean.getSinger());
                ((ListItemViewHolder)holder).datetv.setText(bean.getCrttm());
                if(bean.getUpCollect()!=null) {
                    ((ListItemViewHolder) holder).commenttv.setText("回复 "+bean.getUpCollect().getUpsinger()+":"+bean.getNote());
                    ((ListItemViewHolder) holder).reply_commenttv.setVisibility(View.VISIBLE);
                    ((ListItemViewHolder) holder).reply_commenttv.setText(bean.getUpCollect().getUpsinger()+":"
                            +bean.getUpCollect().getUpnote());
                }else{
                    ((ListItemViewHolder) holder).commenttv.setText(bean.getNote());
                    ((ListItemViewHolder) holder).reply_commenttv.setVisibility(View.GONE);
                }
                ImageLoader.getInstance().displayImage(bean.getUserimgurl(), ((ListItemViewHolder)holder).headiv);
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = holder.getLayoutPosition();
                        mOnItemClickListener.onItemClick(v,pos);
                    }
                });
            }
        }

        @Override
        public int getItemViewType(int position) {
            return position;
        }

        public void setData(ArrayList<CollBean> mData) {
            this.mData = mData;
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }

        class ListItemViewHolder extends RecyclerView.ViewHolder {
            TextView nametv, datetv, praise_num_tv, commenttv, reply_commenttv;
            ImageView headiv, praiseiv;

            public ListItemViewHolder(View view) {
                super(view);
                nametv = (TextView) view.findViewById(R.id.nametv);
                datetv = (TextView) view.findViewById(R.id.datetv);
                praise_num_tv = (TextView) view.findViewById(R.id.praise_num_tv);
                commenttv = (TextView) view.findViewById(R.id.commenttv);
                reply_commenttv = (TextView) view.findViewById(R.id.reply_commenttv);
                headiv = (CircleImageView) view.findViewById(R.id.headiv);
                praiseiv = (ImageView) view.findViewById(R.id.praiseiv);
            }
        }
    }
}
